package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.devicecontroller.test;

import java.io.IOException;

import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.io.ModbusTransport;
import net.wimpi.modbus.msg.ModbusMessage;
import net.wimpi.modbus.msg.ModbusRequest;
import net.wimpi.modbus.msg.ModbusResponse;
import net.wimpi.modbus.msg.ModbusUtil;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.msg.WriteSingleRegisterRequest;
import net.wimpi.modbus.msg.WriteSingleRegisterResponse;
import net.wimpi.modbus.procimg.SimpleRegister;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.Device;

public class MocketAutomaticConnectionModbusTransport implements ModbusTransport{
	private Device dev;
	private MocketPoolingModbusTransport tran;
	private boolean auth = false;
	private int reqs = 0;
	private int unitID;
	private int transID;
	public MocketAutomaticConnectionModbusTransport(Device dev, MocketPoolingModbusTransport tran){
		this.dev = dev;
		this.tran = tran;
	}
	@Override
	public void close() throws IOException {
		tran.close();
		
	}
	@Override
	public ModbusRequest readRequest() throws ModbusIOException {
		if(auth)
			return tran.readRequest();
		throw new ModbusIOException();
	}
	@Override
	public ModbusResponse readResponse() throws ModbusIOException {
		if(auth)
			return tran.readResponse();
		if(reqs == 1){
			ReadInputRegistersResponse res = new ReadInputRegistersResponse(new SimpleRegister[]{new SimpleRegister(dev.getID())});
			ModbusUtil.setFunctionCode(res, Modbus.READ_INPUT_REGISTERS);
			res.setUnitID(unitID);
			res.setTransactionID(transID);
			return res;
		}
		if(reqs == 2){
			WriteSingleRegisterResponse res = new WriteSingleRegisterResponse(0,1);
			ModbusUtil.setFunctionCode(res, Modbus.WRITE_SINGLE_REGISTER);
			res.setUnitID(unitID);
			res.setTransactionID(transID);
			auth = true;
			return res;
		}
		throw new ModbusIOException();
	}
	@Override
	public void writeMessage(ModbusMessage msg) throws ModbusIOException {
		if(auth){
			tran.writeMessage(msg);
			return;
		}
		if(reqs++ == 0){
			if(msg instanceof ReadInputRegistersRequest){
				this.unitID = msg.getUnitID();
				this.transID = msg.getTransactionID();
			}
			else{
				throw new ModbusIOException();
			}
		}
		else if(reqs++ == 1){
			if(msg instanceof WriteSingleRegisterRequest){
				this.unitID = msg.getUnitID();
				this.transID = msg.getTransactionID();
			}
			else{
				throw new ModbusIOException();
			}
		}
		throw new ModbusIOException();
	}
	
}
